// pages/showJobList/showJobList.js
const db = wx.cloud.database({
    env: 'work1-0g1b3grp436e9236'
})
const dayjs = require('../../miniprogram_npm/miniprogram_npm/dayjs/index')
const util= require('../../utils/util.js')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        jobList: [],
        curPage: 0,
        loading: true
    },

    async getJobList(orderBy = 'salary', order = 'desc', limit = 5) {
        let res = await db.collection('work_job').skip(this.data.curPage * limit).limit(limit)
            .where({
                status: 1
            }).orderBy(orderBy, order).get()
        let jobList = res.data
        for (let i = 0; i < jobList.length; i++) {
            const job = jobList[i]
            jobList[i].endTime = dayjs(job.endTime).format("YYYY-MM-DD")
            const res = await db.collection('work_user').doc(job.userId).get()
            jobList[i].user = res.data
        }
        this.setData({
            jobList: this.data.jobList.concat(jobList),
            loading: false
        })
        console.log(jobList)
    },

    async getJobList2(limit = 10) {
        let res = await db.collection('work_job').skip(this.data.curPage * limit).limit(limit)
            .where({
                status: 1
            }).get()
        let jobList = res.data
        for (let i = 0; i < jobList.length; i++) {
            const job = jobList[i]
            jobList[i].endTime = dayjs(job.endTime).format("YYYY-MM-DD")
            const res = await db.collection('work_user').doc(job.userId).get()
            jobList[i].user = res.data
            // 计算距离
            jobList[i].distance = this.getDistance(this.data.latitude, this.data.longitude, job.locationGeo.latitude, job.locationGeo.longitude)
            let s = jobList[i].distance
            if (parseInt(s) >= 1) {
                jobList[i].distanceStr = parseFloat(s).toFixed(1) + "km";
            } else {
                jobList[i].distanceStr = s * 1000 + "m";
            }
        }
        // 合并重排list
        let old = this.data.jobList
        jobList = old.concat(jobList)
        function sortRule(a,b) {
            return a.distance - b.distance
        }
        jobList.sort(sortRule)
        this.setData({
            jobList: jobList,
            loading: false
        })
    },

    rad (d) {
        return d * Math.PI / 180.0;
    },

    getDistance(lat1, lng1, lat2, lng2) {
        var radLat1 = this.rad(lat1);
        var radLat2 = this.rad(lat2);
        var a = radLat1 - radLat2;
        var b = this.rad(lng1) - this.rad(lng2);
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137 // EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000; //输出为公里
        s = s.toFixed(4)
        return s
    },    
    

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let toNum = parseInt(options.to)
        this.setData({
            toNum: toNum
        })
        if (toNum === 1) {
            this.getJobList('updateTime')
        } else if (toNum === 2) {
            this.getJobList('postNum')
        } else if (toNum === 3) {
            // 距离最近
            wx.getLocation({ // 获取当前位置
                type: 'gcj02' // gcj02火星坐标系，用于地图标记点位
            }).then(async res => { // 获取成功
                const {
                    latitude,
                    longitude
                } = res // 如果传入为空，则使用data内数据
                // console.log("经纬度：" + longitude + ", " + latitude)
                this.setData({
                    longitude,
                    latitude
                })
            })
            this.getJobList2()
        } else if (toNum === 4) {
            this.getJobList('continueTime')
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    async onPullDownRefresh() {
        wx.showNavigationBarLoading()
        this.setData({
            jobList: [],
            curPage: 0,
            loading: true
        })
        if (this.data.toNum === 1) {
            this.getJobList('updateTime')
        } else if (this.data.toNum === 2) {
            this.getJobList('postNum')
        } else if (this.data.toNum === 3) {
            this.getJobList2()
        } else if (this.data.toNum === 4) {
            this.getJobList('continueTime')
        }
        wx.hideNavigationBarLoading()
        // 数据成功后，停止下拉刷新
        wx.stopPullDownRefresh()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    async onReachBottom() {
        wx.showLoading({
            title: '加载中..',
        })
        this.setData({
            curPage: this.data.curPage + 1
        })
        if (this.data.toNum === 1) {
            await this.getJobList('updateTime')
        } else if (this.data.toNum === 2) {
            await this.getJobList('postNum')
        } else if (this.data.toNum === 3) {
            await this.getJobList2()
        } else if (this.data.toNum === 4) {
            await this.getJobList('continueTime')
        }
        // 数据成功后，停止下拉刷新
        wx.stopPullDownRefresh()
        wx.hideLoading()
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})